import React, { useRef } from 'react';
import { useNavigate } from 'react-router-dom';
import { Layout, Menu } from 'antd';
import MenuConfigList from '../../config/homeData';
import { HomeOutlined, ShopOutlined, UserOutlined, GoldOutlined } from '@ant-design/icons';
import './index.css';

const { Sider } = Layout;

const iconToElement = (name) => {
  switch (name) {
    case 'HomeOutlined':
      return <HomeOutlined />;
    case 'ShopOutlined':
      return <ShopOutlined />;
    case 'UserOutlined':
      return <UserOutlined />;
    case 'GoldOutlined':
      return <GoldOutlined />;
    default:
      return null;
  }
};

const CommonAside = ({ collapsed }) => {
  const navigate = useNavigate();
  // 创建 Sider 的 ref
  const siderRef = useRef(null);
  const handleMenuClick = (path) => {
    navigate(path); // 使用 navigate 实现路由跳转
  };

  // 递归渲染菜单
  const renderMenuItems = (menuList) => {
    return menuList.map((item) => (
      item.items ? (
        <Menu.SubMenu key={item.path} title={item.label} icon={iconToElement(item.icon)}>
          {renderMenuItems(item.items)}  {/* 递归子菜单 */}
        </Menu.SubMenu>
      ) : (
        <Menu.Item key={item.path} icon={iconToElement(item.icon)} onClick={() => handleMenuClick(item.path)}>
          {item.label}
        </Menu.Item>
      )
    ));
  };

  return (
    <Layout>
      <Sider ref={siderRef} trigger={null} collapsed={collapsed}>
        <div className='headerTitle'>
          {collapsed ? '组件' : 'React组件管理系统'}
        </div>
        <Menu
          theme="dark"
          mode="inline"
          defaultSelectedKeys={['/LayoutPage/home']} // 设置默认选中的菜单
          style={{ height: '100vh' }}
        >
          {renderMenuItems(MenuConfigList)}  {/* 渲染菜单 */}
        </Menu>
      </Sider>
    </Layout>
  );
};

export default CommonAside;
